import {defineStore} from 'pinia'
import { sendSock, createWebSocket, closeSock } from "../common/ws.js"
import { ref } from 'vue'

export const websocketStore = defineStore('websocket', () => {
	/**
	 * socket推送过来的全量数据，暴露出去用户对数据变更的监听
	 */
	const serviceMsg = ref({});

	/**
	 * 连接webSocket init,如果连接断开,重新建立连接
	 */
	const init = () => {
		createWebSocket(global_callback);
	};

	/**
	 * websocket的回调函数
	 * @param jsonMsg 表示收到的消息
	 */
	const global_callback = (jsonMsg) => {
		serviceMsg.value = jsonMsg;
		console.log(jsonMsg);
	};

	/**
	 * webSocket发送消息
	 * @param sendData 发送的json数据
	 */
	const send = (sendData) => {
		sendSock(JSON.stringify(sendData));
	};

	/**
	 * 关闭webSocket
	 */
	const close = ({ isActiveClose = false }) => {
		closeSock({ activeClose: isActiveClose });
	};

	/**
	 * 关闭后重启socket
	 */
	const closeAndRestart = () => {
		close({ isActiveClose: true });
		init();
	};

	const login = (username, password) => {
		send({"msgType":3000,"reqid":1,"data":{"username":"customer","password":"123456"}})
	}

	return {
		init,
		close,
		closeAndRestart,
		serviceMsg,
		login
	};
});
